var api = require('../config/api.js');
var version = require('../config/version.js');
var app = getApp()

function getTextLength(val) {
  var str = new String(val);
  var bytesCount = 0;
  for (var i = 0, n = str.length; i < n; i++) {
    var c = str.charCodeAt(i);
    if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
      bytesCount += 1;
    } else {
      bytesCount += 2;
    }
  }
  return bytesCount;
}

function mixTextOverflow(str, len) {
  var regexp = /[^\x00-\xff]/g; // 正在表达式匹配中文
  // 当字符串字节长度小于指定的字节长度时
  if (str.replace(regexp, "aa").length <= len) {
    return str;
  }
  // 假设指定长度内都是中文
  var m = Math.floor(len / 2);
  for (var i = m, j = str.length; i < j; i++) {
    // 当截取字符串字节长度满足指定的字节长度
    if (str.substring(0, i).replace(regexp, "aa").length >= len) {
      return str.substring(0, i) + '...';
    }
  }
  return str;
}

//判断char数量是否满足数量
function judgeChartCount(str) {
  var l = str.length;
  var blen = 0;
  for (let i = 0; i < l; i++) {
    if ((str.charCodeAt(i) & 0xff00) != 0) {
      blen++;
    }
    blen++;
  }
  return blen;
}


function formatTime(date) {
  var year = date.getFullYear()
  var month = date.getMonth() + 1
  var day = date.getDate()

  var hour = date.getHours()
  var minute = date.getMinutes()
  var second = date.getSeconds()


  return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}

function formatNumber(n) {
  n = n.toString()
  return n[1] ? n : '0' + n
}

/**
 * 封封微信的的get request
 */
function request(url, method = "GET") {
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      method: method,
      header: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'access_token': wx.getStorageSync('token')
      },
      success: function(res) {
        if (res.statusCode == 200) {
          if (res.data.errno == 401) {
            //需要登录后才可以操作
            let code = null;
            return login().then((res) => {
              code = res.code;
              return getUserInfo();
            }).then((userInfo) => {
              //登录远程服务器
              request(api.AuthLoginByWeixin, {
                code: code,
                userInfo: userInfo
              }, 'POST').then(res => {
                if (res.errno === 0) {
                  //存储用户信息
                  wx.setStorageSync('userInfo', res.data.userInfo);
                  wx.setStorageSync('token', res.data.token);

                  resolve(res);
                } else {
                  reject(res);
                }
              }).catch((err) => {
                reject(err);
              });
            }).catch((err) => {
              reject(err);
            })
          } else {
            resolve(res.data);
          }
        } else {
          reject(res.errMsg);
        }

      },
      fail: function(err) {
        reject(err)
        console.log("failed")
      }
    })
  });
}

/**
 * 封封微信的的put request   
 */
function pututrequest(url, method,data) {
  var contentType = 'application/x-www-form-urlencoded'
  if(method!='GET'){
    contentType = 'application/json'
  }
  return new Promise(function(resolve, reject) {
    wx.request({
      url: url,
      method: method,
      data:data,
      header: {
        'Content-Type': contentType,
        'accessToken': wx.getStorageSync('token'),
        'appVersion': version.appVersion,
        'deviceModel': getApp().globalData.systemInfo.model,
        'platform': 'wx',
        'build':version.build,
        'deviceMachineCode':'',
        'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
        'deviceOSVersion': getApp().globalData.systemInfo.system
      },
      success: function(res) {
        if (res && res.statusCode == 200) { //外层判断是否成功
          if (res.data.code != 200) { //内层具体数据是否成功返回           
            if (res.data.code == 40101 || res.data.code == 40301) {
              let code = null;
              return login().then((res1) => { //userInfo
                code = res1.code;
                wx.getUserInfo({
                  withCredentials: true,
                  success: function(res_user) {
                    // 11
                    wx.request({
                      url: api.userAuth,
                      data: { platform: 'wx', authorizationCode: code, userEncryptrfData: res_user.encryptedData, iv: res_user.iv},
                      method: 'POST',
                      header: {
                        'Content-Type': 'application/json',
                        'accessToken': wx.getStorageSync('token'),
                        'appVersion': version.appVersion,
                        'deviceModel': getApp().globalData.systemInfo.model,
                        'platform': 'wx',
                        'build': version.build,
                        'deviceMachineCode': '',
                        'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                        'deviceOSVersion': getApp().globalData.systemInfo.system,
                      },
                      success: function(res2) {   
                        wx.setStorageSync('token', res2.data.data.token);
                        if (res2 && res2.statusCode == 200 && res2.data.code == 200) { 
                          let userInfo = res2.data.data.user;
                          if (userInfo && !userInfo.avatarUrl) {
                            userInfo.avatarUrl = version.defaultAvataUrl
                          }
                          wx.setStorageSync('userInfo', userInfo);                         
                          wx.setStorageSync('auth', true);                          
                          wx.setStorageSync('hasPhone', true);
                        }   
                        if (res && res.data.code == 301) {
                          wx.setStorageSync('hasPhone', false);
                        }                
                       
                        // 得到token后，再次发起请求
                        wx.request({
                          url: url,
                          method: method,
                          data:data,
                          header: {
                            'Content-Type': contentType,
                            'accessToken': wx.getStorageSync('token'),
                            'appVersion': version.appVersion,
                            'deviceModel': getApp().globalData.systemInfo.model,
                            'platform': 'wx',
                            'build': version.build,
                            'deviceMachineCode': '',
                            'deviceOS': getApp().globalData.systemInfo.system.split(" ")[0],
                            'deviceOSVersion': getApp().globalData.systemInfo.system,
                          },
                          success: function(res3) {                           
                            if (res3.data.code==200) {
                              resolve(res3.data);
                            }
                          }
                        })
                        // 得到token后，再次发起请求
                      }
                    })
                    //11
                  }
                })
              }) //userInfo
            } //4001
          } else {
            resolve(res.data);
          }
        }
      },
      fail: function(err) {
        reject(err)
      }
    })
  });
}


/**
 * 检查微信会话是否过期
 */
function checkSession() {
  return new Promise(function(resolve, reject) {
    wx.checkSession({
      success: function() {
        resolve(true);
      },
      fail: function() {
        reject(false);
      }
    })
  });
}

/**
 * 调用微信登录
 */
function login() {
  return new Promise(function(resolve, reject) {
    wx.login({
      success: function(res) {
        if (res.code) {
          //登录远程服务器
          resolve(res);
        } else {
          reject(res);
        }
      },
      fail: function(err) {
        reject(err);
      }
    });
  });
}

function logintongbu() {
  wx.login({
    success: function(res) {
      if (res.code) {
        //登录远程服务器
        return res.code
      }
    },
    fail: function(err) {

    }
  });

}

function getUserInfo() {
  return new Promise(function(resolve, reject) {
    wx.getUserInfo({
      withCredentials: true,
      success: function(res) {
        resolve(res);
      },
      fail: function(err) {
        reject(err);
      }
    })
  });
}

function getScope(scopeName) {
  return new Promise(function(resolve, reject) {
    //  查询授权
    wx.getSetting({
      success(res) {
        if (res.authSetting[scopeName]) {
          resolve(1);
        } else {
          resolve(0);
        }
      }
    })
  })
}


module.exports = {
  getTextLength,
  mixTextOverflow,
  judgeChartCount,
  formatTime,
  request,
  // putrequest,
  pututrequest,
  // postrequest,
  checkSession,
  login,
  getUserInfo,
  getScope,
}